<template>
<div class="users"> 
  <!--     <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb> -->

        <Breadcrumb />

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            @clear="getUserList"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="dialogVisible = true"
            icon="el-icon-add"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column label="#" type="index" width="50"></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
          width="100"
        ></el-table-column>
        <el-table-column prop="email" label="邮箱" width="160">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="stateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" 
      :filters="[{ text: '家', value: '家' }, { text: '公司', value: '公司' }]"
      :filter-method="filterTag"
      filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showeditUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            >
            </el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content=" 分配角色"
              placement="top-start"
              :enterable="false"

            >
              <el-button @click="showAllotRole(scope.row)" type="warning" icon="el-icon-setting" size="mini">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

<!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      @close="reset"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
        ref="addFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

<!-- 修改用户 -->
    <el-dialog
      title="修改用户"
      @close="resetEdit"
      :visible.sync="editShow"
      width="40%"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
        ref="editFormRef"
      >
        <el-form-item label="用户名" >
          <el-input v-model="editForm.username"  disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>


<!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="showAllot"
      width="50%"
      @close="setClose"
      >
      <div>
              <p>当前的用户: {{userInfo.username}}</p>
        <p>当前的角色: {{userInfo.role_name}}</p>
        <p>分配新角色: 
            <el-select v-model="selectRoId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
        </p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showAllot = false">取 消</el-button>
        <el-button type="primary" @click="saveAllotRole">确 定</el-button>
      </span>
    </el-dialog>




  </div>
</template>

<script>
import Breadcrumb from "../breadcrumb.vue";
export default {
  created() {
    this.getUserList();
  },
  components:{
    Breadcrumb
  },
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    var checkMobile = (rule, value, cb) => {
      const regMobile =
        /^([0|86|17951])?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      dialogVisible: false,
      editShow:false,
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            validator: checkMobile,
            trigger: "blur",
          },
        ],
      },
      editForm:{},
      editFormRules:{
        email: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            validator: checkEmail, trigger: "blur",},
        ],
                mobile: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            validator: checkMobile, trigger: "blur"},
        ],
      },
      showAllot:false,
      //需要被分配角色的用户信息
      userInfo:{},
      // 所有角色
      rolesList:[],
      selectRoId:'',
    };
  },
  methods: {
    filterTag(value, row) {
        return row.tag === value;
      },
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("获取数据失败");
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    async stateChange(userinfo) {
      // console.log(state);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("修改状态失败");
      }
      this.$message.success("更新状态成功");
    },
     addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功");
        this.dialogVisible = false;
        this.getUserList();
      });
    },
    reset() {
      this.$refs.addFormRef.resetFields();
    },
    async showeditUser(id){
        this.editShow = true
        const {data:res} = await this.$http.get('users/'+id)
        if (res.meta.status !== 200) return this.$message.error("获取用户信息失败");
        this.editForm = res.data
    },
    resetEdit(){
        this.$refs.editFormRef.resetFields();
    },
    editUser(){
        this.$refs.editFormRef.validate(async (valid) => {
            if (!valid) return;
            const { data: res } = await this.$http.put("users/"+this.editForm.id, 
                {
                    email:this.editForm.email,
                    mobile:this.editForm.mobile
                }
            );
            if (res.meta.status !== 200) return this.$message.error("编辑用户失败");
            this.$message.success("编辑用户成功");
        this.editShow = false
            this.getUserList();
        });
    },
    async deleteUser(id){
        const confirms = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((err) => err);
         
         if(confirms !== 'confirm'){
             return this.$message.info('已取消删除');  
         }
         const {data:res} = await this.$http.delete('users/'+id)
        if (res.meta.status !== 200) return this.$message.error("删除用户信息失败");
        this.$message.success('删除成功！')
        this.getUserList()
    },
    async showAllotRole(userinfo){
      this.userInfo = userinfo
        // 获取所有角色列表
      const {data:res} = await this.$http.get('roles/')
      if (res.meta.status !== 200) return this.$message.error("获取用户信息失败");
      this.rolesList = res.data
      this.showAllot = true
    },
    async saveAllotRole(){
      if(!this.selectRoId) return this.$message.error('请先选择要分配到哪个角色')
      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,
                {rid:this.selectRoId})
      if (res.meta.status !== 200) return this.$message.error("更新用户角色失败");
      this.$message.success('更新角色成功!')
      this.getUserList()
      this.showAllot = false
    },
    setClose(){
      this.selectRoId = ''
      this.userInfo = {}
    }
  },
};
</script>

<style lang="scss" scoped>
.users {
  .el-card {
    margin-top: 30px;

    .el-table {
      margin: 20px 0;
      .el-table .warning-row {
        background: oldlace;
      }

      .el-table .success-row {
        background: #f0f9eb;
      }
    }
  }
}
</style>